package com.example.license.Interceptor;

import com.example.license.service.ILicenseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 使用拦截器拦截请求，验证证书的可用性
 */
@Slf4j
@Component
public class LicenseCheckInterceptor implements HandlerInterceptor {
    @Autowired
    private ILicenseService service;

    /**
     * 进入controller层之前拦截请求
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验证书是否有效
        boolean verifyResult = service.verify();
        if (verifyResult) {
            return true;
        } else {
            //验证失败跳转到上传证书页面,如果为前后端分离的项目,重定向会有跨域问题,
            //解决方法,此处抛出错误码,前端拦截,跳转页面
            log.info("您的证书无效，请核查服务器是否取得授权或重新申请证书！");
            response.sendRedirect(request.getContextPath() + "/file.html");
            return false;
        }
    }

    /**
     * 处理请求完成后视图渲染之前的处理操作
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        //log.info("处理请求完成后视图渲染之前的处理操作");
    }

    /**
     * 视图渲染之后的操作
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        //log.info("视图渲染之后的操作");
    }

}
